package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SellerServiceImpl implements SellerService {
    @Autowired
    private SellerMapper sellerMapper;
    @Autowired
    private HttpSession httpSession;

    /**
     * 商家注册
     * @param sellerVo
     * @return
     */
    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        if(EmptyUtil.isNullOrEmpty(sellerVo)){
            return null;
        }
        sellerVo.setPassword(MD5Coder.md5Encode(sellerVo.getPassword()));
        int flag = sellerMapper.insert(BeanConv.toBean(sellerVo, Seller.class));
        return flag>0;
    }

    /**
     * 商家登录
     * @param sellerVo
     * @return
     */
    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        if(EmptyUtil.isNullOrEmpty(sellerVo)){
            return null;
        }
        SellerExample sellerExample = new SellerExample();
        sellerExample.createCriteria().andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        List<Seller> sellerList = sellerMapper.selectByExample(sellerExample);
        if(!EmptyUtil.isNullOrEmpty(sellerList)){
            Seller seller = sellerList.get(0);
            SellerVo sellerResult = BeanConv.toBean(seller, sellerVo);
            sellerResult.setSessionId(httpSession.getId());
            httpSession.setAttribute(httpSession.getId(),sellerResult);
            return sellerResult;
        }
        return null;
    }

    /**
     * 退出登录
     */
    @Override
    public void loginOutSeller() {
       httpSession.removeAttribute(httpSession.getId());
    }

    /**
     * 判断是否登录
     * @return
     */
    @Override
    public Boolean isLogin() {
        Object obj = httpSession.getAttribute(httpSession.getId());
        if(EmptyUtil.isNullOrEmpty(obj)){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 根据商家id查询商家用户
     * @param sellerVo
     * @return
     */
    @Override
    public SellerVo findSellerVoById(SellerVo sellerVo) {
        if(EmptyUtil.isNullOrEmpty(sellerVo)){
            return null;
        }
        Seller seller = sellerMapper.selectByPrimaryKey(sellerVo.getId());
        if(EmptyUtil.isNullOrEmpty(seller)){
            return null;
        }
        return BeanConv.toBean(seller,SellerVo.class);
    }
}
